package com.ucode.wap.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.cgms.service.CgmsCompanionCommentService;
import com.ucode.cgms.service.CgmsCompanionOrderService;
import com.ucode.cgms.service.CgmsCompanionProductService;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.member.service.MemberService;
import com.ucode.model.cgms.CgmsCompanionComment;
import com.ucode.model.cgms.CgmsCompanionOrder;
import com.ucode.model.cgms.CgmsCompanionProduct;
import com.ucode.model.cgms.CgmsCompanionUser;
import com.ucode.model.cgms.convert.CgmsCompanionCommentConvert;
import com.ucode.model.cgms.enums.CgmsCompanionOrderStatusEnum;
import com.ucode.model.cgms.enums.CgmsSysResultCodeEnum;
import com.ucode.model.cgms.form.CgmsCompanionCommentCreateForm;
import com.ucode.model.cgms.form.CgmsCompanionCommentReplyForm;
import com.ucode.model.cgms.vo.CgmsCompanionCommentVO;
import com.ucode.model.member.Member;
import com.ucode.tool.annotation.NeedLogin;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.CollectionUtils;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 移动端 - 陪玩社区系统 - 陪玩评论接口
 * 
 * @Author: system
 * @Date: 2025/01/15 10:00
 * @Version: 1.0
 */
@Tag(name = "移动端 - 陪玩社区系统 - 陪玩评论")
@RestController
@RequestMapping("/cgms/companion-comment")
@Validated
public class ApiCgmsCompanionCommentController {

    private static Log log = LogFactory.get();
    
    @Resource
    private CgmsCompanionCommentService cgmsCompanionCommentService;
    
    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;
    
    @Resource
    private MemberService memberService;
    
    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;
    
    @Resource
    private CgmsCompanionProductService cgmsCompanionProductService;
    @Resource
    private CgmsCompanionOrderService cgmsCompanionOrderService;

    @NeedLogin
    @Operation(summary = "陪玩用户公共评价分页列表")
    @GetMapping(value = "/companion-user/page-list")
    public ResponseResult<Paginator<CgmsCompanionCommentVO>> pageListByCompanionUser(
            @Schema(description = "陪玩用户ID",  requiredMode = Schema.RequiredMode.REQUIRED) @RequestParam(value = "companionUserId", required = true) Long companionUserId,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        Map<String, Object> condition = new HashMap<>();
        condition.put("companionUserId", companionUserId);
        condition.put("visible", true);
        condition.put("deltag", false);

        Paginator<CgmsCompanionComment> paginator = cgmsCompanionCommentService.queryPageForList(condition, pageSize, pageNum);
        Paginator<CgmsCompanionCommentVO> paginatorVO = CgmsCompanionCommentConvert.INSTANCE.convertPage(paginator);
        if(CollUtil.isNotEmpty(paginatorVO.getList())){
            Set<Long> userIds = CollectionUtils.convertSet(paginatorVO.getList(), CgmsCompanionCommentVO::getUserId);
            Map<Long, Member>  memberMap = memberService.getMap(userIds);

            for(CgmsCompanionCommentVO vo : paginatorVO.getList()){
                Member member = memberMap.get(vo.getUserId());
                if(ObjectUtil.isNotNull(member)){
                    vo.setUserNickname(member.getNickname());
                    vo.setUserAvatar(member.getAvatar());
                }
            }
        }

        return ResponseResult.success(paginatorVO);
    }

    @NeedLogin(validate = true)
    @PostMapping("/create")
    @Operation(summary = "提交评论")
    public ResponseResult<Long> create(@Valid @RequestBody CgmsCompanionCommentCreateForm form) {
        CgmsCompanionComment companionComment = CgmsCompanionCommentConvert.INSTANCE.convert(form);
        CgmsCompanionOrder companionOrder = cgmsCompanionOrderService.validate(form.getOrderId(),currentLoginUserHandler.getCurrentUserId());
        if(!ObjUtil.equals(companionOrder.getStatus(),  CgmsCompanionOrderStatusEnum.COMPLETED.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_COMMENT_FAIL_STATUS_NOT_COMPLETED);
        }
        companionComment.setUserId(companionOrder.getMemberId());
        companionComment.setCompanionProductId(companionOrder.getProductId());
        companionComment.setCompanionUserId(companionOrder.getServiceUserId());
        companionComment.setVisible(true);
        companionComment.setReplyStatus(false);

        Long commentId = cgmsCompanionCommentService.insert(companionComment);
        return ResponseResult.success(commentId);
    }


    @NeedLogin(validate = true)
    @PostMapping("/reply")
    @Operation(summary = "评论回复")
    public ResponseResult<Long> reply(@Valid @RequestBody CgmsCompanionCommentReplyForm form) {

        CgmsCompanionComment companionComment = cgmsCompanionCommentService.validate(form.getCommentId());
        if(!ObjUtil.equals(companionComment.getCompanionUserId(), currentLoginUserHandler.getCurrentUserId())){
            throw  new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        CgmsCompanionComment updateBean = new CgmsCompanionComment();
        updateBean.setId(form.getCommentId());
        updateBean.setReplyStatus(true);
        updateBean.setReplyContent(form.getReplyContent());
        updateBean.setReplyTime(LocalDateTime.now());
        cgmsCompanionCommentService.update(updateBean);
        return ResponseResult.success();
    }



    @NeedLogin
    @Operation(summary = "我的评价分页列表")
    @GetMapping(value = "/my-comment/page-list")
    public ResponseResult<Paginator<CgmsCompanionCommentVO>> pageListByMyComment(
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Map<String, Object> condition = new HashMap<>();
        condition.put("userId", currentLoginUserHandler.getCurrentUserId());
        condition.put("visible", true);
        condition.put("deltag", false);

        Paginator<CgmsCompanionComment> paginator = cgmsCompanionCommentService.queryPageForList(condition, pageSize, pageNum);
        Paginator<CgmsCompanionCommentVO> paginatorVO = CgmsCompanionCommentConvert.INSTANCE.convertPage(paginator);
        if(CollUtil.isNotEmpty(paginatorVO.getList())){
            Set<Long> userIds = CollectionUtils.convertSet(paginatorVO.getList(), CgmsCompanionCommentVO::getCompanionUserId);
            Map<Long, Member>  memberMap = memberService.getMap(userIds);

            for(CgmsCompanionCommentVO vo : paginatorVO.getList()){
                Member member = memberMap.get(vo.getCompanionUserId());
                if(ObjectUtil.isNotNull(member)){
                    vo.setCompanionUserNickname(member.getNickname());
                    vo.setCompanionUserAvatar(member.getAvatar());
                }
            }
        }
        return ResponseResult.success(paginatorVO);
    }


    @NeedLogin
    @Operation(summary = "评价我的分页列表")
    @GetMapping(value = "/comment-me/page-list")
    public ResponseResult<Paginator<CgmsCompanionCommentVO>> pageListByCommentMe(
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Map<String, Object> condition = new HashMap<>();
        condition.put("companionUserId", currentLoginUserHandler.getCurrentUserId());
        condition.put("visible", true);
        condition.put("deltag", false);

        Paginator<CgmsCompanionComment> paginator = cgmsCompanionCommentService.queryPageForList(condition, pageSize, pageNum);
        Paginator<CgmsCompanionCommentVO> paginatorVO = CgmsCompanionCommentConvert.INSTANCE.convertPage(paginator);
        if(CollUtil.isNotEmpty(paginatorVO.getList())){
            Set<Long> userIds = CollectionUtils.convertSet(paginatorVO.getList(), CgmsCompanionCommentVO::getUserId);
            Map<Long, Member>  memberMap = memberService.getMap(userIds);

            for(CgmsCompanionCommentVO vo : paginatorVO.getList()){
                Member member = memberMap.get(vo.getUserId());
                if(ObjectUtil.isNotNull(member)){
                    vo.setUserNickname(member.getNickname());
                    vo.setUserAvatar(member.getAvatar());
                }
            }
        }

        return ResponseResult.success(paginatorVO);
    }


    /**
     * 转换分页数据并填充关联信息
     *
     * @param paginator 评论分页数据
     * @return VO分页数据
     */
    private Paginator<CgmsCompanionCommentVO> pageList(Paginator<CgmsCompanionComment> paginator) {
        Paginator<CgmsCompanionCommentVO> paginatorVO = CgmsCompanionCommentConvert.INSTANCE.convertPage(paginator);
        List<CgmsCompanionCommentVO> list = paginatorVO.getList();
        
        if (CollUtil.isNotEmpty(list)) {
            Set<Long> userIds = new HashSet<>();
            Set<Long> companionUserIds = new HashSet<>();
            Set<Long> productIds = new HashSet<>();
            
            // 收集所有ID
            for (CgmsCompanionCommentVO vo : list) {
                if (ObjectUtil.isNotNull(vo.getUserId())) {
                    userIds.add(vo.getUserId());
                }
                if (ObjectUtil.isNotNull(vo.getCompanionUserId())) {
                    companionUserIds.add(vo.getCompanionUserId());
                }
                if (ObjectUtil.isNotNull(vo.getCompanionProductId())) {
                    productIds.add(vo.getCompanionProductId());
                }
            }
            
            // 批量查询
            Map<Long, Member> memberMap = memberService.getMap(userIds);
            Map<Long, CgmsCompanionUser> companionUserMap = cgmsCompanionUserService.getMap(companionUserIds);
            Map<Long, CgmsCompanionProduct> productMap = cgmsCompanionProductService.getMap(productIds);
            
            // 填充数据
            for (CgmsCompanionCommentVO vo : list) {
                enrichCommentVO(vo, memberMap, companionUserMap, productMap);
            }
        }
        
        return paginatorVO;
    }
    
    /**
     * 丰富评论VO对象信息
     *
     * @param commentVO 评论VO对象
     */
    private void enrichCommentVO(CgmsCompanionCommentVO commentVO) {
        if (ObjectUtil.isNull(commentVO)) {
            return;
        }
        // 用户信息
        if (ObjectUtil.isNotNull(commentVO.getUserId())) {
            Member member = memberService.selectByPrimaryKey(commentVO.getUserId());
            if (ObjectUtil.isNotNull(member)) {
                commentVO.setUserNickname(member.getNickname());
                commentVO.setUserAvatar(member.getAvatar());
            }
        }
        
        // 陪玩用户信息
        if (ObjectUtil.isNotNull(commentVO.getCompanionUserId())) {
            CgmsCompanionUser companionUser = cgmsCompanionUserService.selectByPrimaryKey(commentVO.getCompanionUserId());
            if (ObjectUtil.isNotNull(companionUser)) {
                commentVO.setCompanionUserNickname(companionUser.getNickName());
                commentVO.setCompanionUserAvatar(companionUser.getAvatar());
            }
        }
        
        // 商品信息
        if (ObjectUtil.isNotNull(commentVO.getCompanionProductId())) {
            CgmsCompanionProduct product = cgmsCompanionProductService.selectByPrimaryKey(commentVO.getCompanionProductId());
            if (ObjectUtil.isNotNull(product)) {
                commentVO.setCompanionProductName(product.getTitle());
            }
        }
    }
    
    /**
     * 批量丰富评论VO对象信息
     *
     * @param commentVO 评论VO对象
     * @param memberMap 用户映射
     * @param companionUserMap 陪玩用户映射
     * @param productMap 产品映射
     */
    private void enrichCommentVO(CgmsCompanionCommentVO commentVO, Map<Long, Member> memberMap, 
                                Map<Long, CgmsCompanionUser> companionUserMap, 
                                Map<Long, CgmsCompanionProduct> productMap) {
        if (ObjectUtil.isNull(commentVO)) {
            return;
        }
        
        // 填充用户信息
        if (ObjectUtil.isNotNull(commentVO.getUserId()) && !commentVO.getAnonymous()) {
            Member member = memberMap.get(commentVO.getUserId());
            if (ObjectUtil.isNotNull(member)) {
                commentVO.setUserNickname(member.getNickname());
                commentVO.setUserAvatar(member.getAvatar());
            }
        }
        
        // 填充陪玩用户信息
        if (ObjectUtil.isNotNull(commentVO.getCompanionUserId())) {
            CgmsCompanionUser companionUser = companionUserMap.get(commentVO.getCompanionUserId());
            if (ObjectUtil.isNotNull(companionUser)) {
                commentVO.setCompanionUserNickname(companionUser.getNickName());
                commentVO.setCompanionUserAvatar(companionUser.getAvatar());
            }
        }
        
        // 填充商品信息
        if (ObjectUtil.isNotNull(commentVO.getCompanionProductId())) {
            CgmsCompanionProduct product = productMap.get(commentVO.getCompanionProductId());
            if (ObjectUtil.isNotNull(product)) {
                commentVO.setCompanionProductName(product.getTitle());
            }
        }
    }
}
